// API相关功能

// 辅助函数：带认证的API请求
async function fetchAuthenticatedApi(url, options = {}) {
    const defaultOptions = {
        headers: {
            'Content-Type': 'application/json'
        },
        credentials: 'same-origin'
    };

    const mergedOptions = {
        ...defaultOptions,
        ...options,
        headers: {
            ...defaultOptions.headers,
            ...options.headers
        }
    };

    return fetch(url, mergedOptions);
}

// 获取当前配送员信息
async function fetchDeliveryPersonInfo() {
    try {
        const response = await fetchAuthenticatedApi(`${API_BASE_URL}/me`);
        if (response.ok) {
            currentDeliveryPerson = await response.json();
            updateDeliveryPersonUI();
        } else {
            throw new Error('获取配送员信息失败');
        }
    } catch (error) {
        console.error('获取配送员信息失败:', error);
        showAlert('获取配送员信息失败，请刷新页面重试。', 'danger');
    }
}

// 加载我的订单
async function loadMyOrders() {
    ordersLoader.style.display = 'block';
    noOrdersMessage.style.display = 'none';
    ordersList.innerHTML = '';

    try {
        const response = await fetchAuthenticatedApi(`${API_BASE_URL}/orders`);
        if (response.ok) {
            const orders = await response.json();
            displayOrders(orders);
        } else {
            throw new Error('获取订单列表失败');
        }
    } catch (error) {
        console.error('获取订单列表失败:', error);
        showAlert('获取订单列表失败，请刷新页面重试。', 'danger');
    } finally {
        ordersLoader.style.display = 'none';
    }
}

// 查看订单详情
async function viewOrderDetail(orderNumber) {
    if (!orderNumber) return;

    showLoader(true);
    try {
        // 保存当前订单号
        currentOrderNumber = orderNumber;

        // 获取订单详情
        const orderResponse = await fetchAuthenticatedApi(`/api/v1/orders/${orderNumber}`);
        if (!orderResponse.ok) {
            throw new Error('获取订单详情失败');
        }
        const order = await orderResponse.json();

        // 获取物流轨迹
        const tracesResponse = await fetchAuthenticatedApi(`${API_BASE_URL}/orders/${orderNumber}/traces`);
        let traces = [];
        if (tracesResponse.ok) {
            traces = await tracesResponse.json();
        }

        // 获取路径坐标
        const pathResponse = await fetchAuthenticatedApi(`/api/v1/orders/${orderNumber}/path`);
        let pathCoordinates = [];
        if (pathResponse.ok) {
            pathCoordinates = await pathResponse.json();
        }

        // 显示订单详情
        displayOrderDetails(order);
        // 显示物流轨迹
        displayLogisticsTraces(traces);
        // 更新状态选择框
        updateStatusOptions(order.status);
        // 初始化路线地图
        initOrderRouteMap(pathCoordinates);
        // 自动获取当前位置并填充
        fillCurrentLocation();
        // 显示订单详情视图
        showOrderDetailView();
    } catch (error) {
        console.error('查看订单详情失败:', error);
        showAlert('查看订单详情失败: ' + error.message, 'danger');
    } finally {
        showLoader(false);
    }
}

// 处理更新状态
async function handleUpdateStatus(event) {
    event.preventDefault();
    if (!currentOrderNumber) return;

    const newStatus = newStatusSelect.value;
    const location = locationInput.value.trim();
    const description = descriptionInput.value.trim();

    if (!newStatus) {
        showAlert('请选择新状态', 'warning');
        return;
    }

    if (!location) {
        showAlert('请输入当前位置', 'warning');
        return;
    }

    showLoader(true);
    try {
        const response = await fetchAuthenticatedApi(
            `${API_BASE_URL}/orders/${currentOrderNumber}/status?newStatus=${newStatus}&location=${encodeURIComponent(location)}&description=${encodeURIComponent(description)}`,
            {
                method: 'PUT'
            }
        );

        if (response.ok) {
            const updatedOrder = await response.json();
            showAlert('订单状态已更新', 'success');
            // 重新加载订单详情
            viewOrderDetail(currentOrderNumber);
        } else {
            const errorData = await response.json();
            throw new Error(errorData.message || '更新订单状态失败');
        }
    } catch (error) {
        console.error('更新订单状态失败:', error);
        showAlert('更新订单状态失败: ' + error.message, 'danger');
    } finally {
        showLoader(false);
    }
}

// 更新配送员状态
async function updateDeliveryPersonStatus(status) {
    showLoader(true);
    try {
        const response = await fetchAuthenticatedApi(
            `${API_BASE_URL}/status?status=${status}`,
            {
                method: 'PUT'
            }
        );

        if (response.ok) {
            const updatedPerson = await response.json();
            currentDeliveryPerson = updatedPerson;
            updateDeliveryPersonUI();
            showAlert(`状态已更新为: ${formatDeliveryPersonStatus(status)}`, 'success');
        } else {
            const errorData = await response.json();
            throw new Error(errorData || '更新状态失败');
        }
    } catch (error) {
        console.error('更新状态失败:', error);
        showAlert('更新状态失败: ' + error.message, 'danger');
    } finally {
        showLoader(false);
    }
}

// 更新当前位置
async function updateCurrentLocation() {
    if (!navigator.geolocation) {
        showAlert('您的浏览器不支持地理位置功能', 'warning');
        return;
    }

    showLoader(true);
    navigator.geolocation.getCurrentPosition(
        async (position) => {
            try {
                const longitude = position.coords.longitude;
                const latitude = position.coords.latitude;

                const response = await fetchAuthenticatedApi(
                    `${API_BASE_URL}/location?longitude=${longitude}&latitude=${latitude}`,
                    {
                        method: 'PUT'
                    }
                );

                if (response.ok) {
                    const updatedPerson = await response.json();
                    currentDeliveryPerson = updatedPerson;
                    updateCurrentLocationOnMap(longitude, latitude);
                    showAlert('位置已更新', 'success');
                } else {
                    const errorData = await response.json();
                    throw new Error(errorData || '更新位置失败');
                }
            } catch (error) {
                console.error('更新位置失败:', error);
                showAlert('更新位置失败: ' + error.message, 'danger');
            } finally {
                showLoader(false);
            }
        },
        (error) => {
            showLoader(false);
            console.error('获取地理位置失败:', error);
            let errorMessage = '获取地理位置失败';
            switch (error.code) {
                case error.PERMISSION_DENIED:
                    errorMessage += ': 用户拒绝了地理位置请求';
                    break;
                case error.POSITION_UNAVAILABLE:
                    errorMessage += ': 位置信息不可用';
                    break;
                case error.TIMEOUT:
                    errorMessage += ': 获取位置超时';
                    break;
                case error.UNKNOWN_ERROR:
                    errorMessage += ': 未知错误';
                    break;
            }
            showAlert(errorMessage, 'warning');
        },
        {
            enableHighAccuracy: true,
            timeout: 10000,
            maximumAge: 0
        }
    );
}

// 加载可接单订单
async function loadAvailableOrders() {
    availableOrdersLoader.style.display = 'block';
    noAvailableOrdersMessage.style.display = 'none';
    availableOrdersList.innerHTML = '';

    try {
        const response = await fetchAuthenticatedApi(`${API_BASE_URL}/available-orders`);
        if (response.ok) {
            const orders = await response.json();
            displayAvailableOrders(orders);
        } else {
            throw new Error('获取可接单列表失败');
        }
    } catch (error) {
        console.error('获取可接单列表失败:', error);
        showAlert('获取可接单列表失败，请刷新页面重试。', 'danger');
    } finally {
        availableOrdersLoader.style.display = 'none';
    }
}

// 接单函数
async function acceptOrder(orderNumber) {
    showLoader(true);
    try {
        const response = await fetchAuthenticatedApi(
            `${API_BASE_URL}/orders/${orderNumber}/accept`,
            {
                method: 'POST'
            }
        );

        if (response.ok) {
            const updatedOrder = await response.json();
            showAlert('接单成功！', 'success');
            
            // 从新订单列表中移除
            newOrdersMap.delete(orderNumber);
            updateNewOrdersUI();
            
            // 重新加载我的订单列表
            await loadMyOrders();
        } else {
            const errorData = await response.json();
            throw new Error(errorData || '接单失败');
        }
    } catch (error) {
        console.error('接单失败:', error);
        showAlert('接单失败: ' + error.message, 'danger');
    } finally {
        showLoader(false);
    }
}

// 获取工作统计数据
async function loadWorkStatistics() {
    const workStatsElement = document.getElementById('workStats');
    
    try {
        const response = await fetchAuthenticatedApi(`${API_BASE_URL}/statistics`);
        if (response.ok) {
            const statistics = await response.json();
            displayWorkStatistics(statistics, workStatsElement);
        } else {
            throw new Error('获取工作统计数据失败');
        }
    } catch (error) {
        console.error('获取工作统计数据失败:', error);
        workStatsElement.innerHTML = `
            <div class="alert alert-danger" role="alert">
                <i class="bi bi-exclamation-triangle-fill me-2"></i>获取工作统计数据失败
            </div>
            <button class="btn btn-outline-primary btn-sm" onclick="loadWorkStatistics()">
                <i class="bi bi-arrow-clockwise me-1"></i>重试
            </button>
        `;
    }
}